package com.zcx.yun;

import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.util.Log;
import android.widget.Toast;

import com.yuntongxun.ecsdk.ECChatManager;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECGroupManager;
import com.yuntongxun.ecsdk.ECInitParams;
import com.yuntongxun.ecsdk.ECMessage;
import com.yuntongxun.ecsdk.OnChatReceiveListener;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.ecsdk.im.ECMessageNotify;
import com.yuntongxun.ecsdk.im.ECTextMessageBody;
import com.yuntongxun.ecsdk.im.group.ECGroupNoticeMessage;

import java.util.List;

public final class YunAction {

    private YunAction(){}

    public static YunAction getInstance() {

        return YunActionHolder.Instance;

    }

    private static class YunActionHolder {

        private static final YunAction Instance = new YunAction();

    }

    private String app_key = "8a216da857087494015708a79a2f007f";

    private String token = "6ea29c87f1152f60dacb4a3b757f77ae";

    private String userId, groupId = "gg801623561";

    private YunCallBack yunCallBack;

    public void initia(Context context, ECDevice.InitListener initListener){

        if(!ECDevice.isInitialized()) {

            ECDevice.initial(context, initListener);

        }

    }

    public void login(final Context context, final String userId) {

        if(!ECDevice.isInitialized()) {

            Toast.makeText(context, "长连接初始化失败", Toast.LENGTH_SHORT).show();

            return;

        }

        ECInitParams params = ECInitParams.createParams();

        params.setUserid(YunAction.this.userId = userId);

        params.setAppKey(app_key);

        params.setToken(token);

        params.setAuthType(ECInitParams.LoginAuthType.NORMAL_AUTH);

        params.setMode(ECInitParams.LoginMode.FORCE_LOGIN);

        params.setOnDeviceConnectListener(new ECDevice.OnECDeviceConnectListener() {

            public void onConnect() {

            }

            @Override
            public void onDisconnect(ECError error) {

            }

            @Override
            public void onConnectState(ECDevice.ECConnectState state, ECError error) {

                if (yunCallBack == null) {

                    Toast.makeText(context, "请注册YunCallBack监听", Toast.LENGTH_SHORT).show();

                    return;

                }

                if (state == ECDevice.ECConnectState.CONNECT_FAILED) {

                    if (error.errorCode == SdkErrorCode.SDK_KICKED_OFF) {

                        yunCallBack.otherLogin();

                    } else {

                        yunCallBack.connError();

                    }

                } else if (state == ECDevice.ECConnectState.CONNECT_SUCCESS) {

                    yunCallBack.loginSucceed();

                    ECGroupManager groupManager = ECDevice.getECGroupManager();

                    groupManager.joinGroup(groupId, "" , new ECGroupManager.OnJoinGroupListener() {

                        @Override
                        public void onJoinGroupComplete(ECError error, String groupId) {

                        }

                    });

                    ECDevice.setOnChatReceiveListener(new OnChatReceiveListener() {

                        @Override
                        public void OnReceivedMessage(ECMessage ecMessage) {

                            yunCallBack.onReceivedMessage(ecMessage);

                        }

                        @Override
                        public void OnReceiveGroupNoticeMessage(ECGroupNoticeMessage ecGroupNoticeMessage) {

                        }

                        @Override
                        public void onReceiveMessageNotify(ECMessageNotify ecMessageNotify) {

                        }

                        @Override
                        public void onOfflineMessageCount(int i) {

                        }

                        @Override
                        public int onGetOfflineMessage() {

                            return 0;

                        }

                        @Override
                        public void onReceiveOfflineMessage(List<ECMessage> list) {

                        }

                        @Override
                        public void onReceiveOfflineMessageCompletion() {

                        }

                        @Override
                        public void onServicePersonVersion(int i) {

                        }

                        @Override
                        public void onReceiveDeskMessage(ECMessage ecMessage) {

                        }

                        @Override
                        public void onSoftVersion(String s, int i) {

                        }

                    });

                }

            }

        });

        ECDevice.login(params);

    }

    public void logout(Context context, ECDevice.OnLogoutListener onLogoutListener){

        ECDevice.logout(onLogoutListener);

        userId = null;

    }

    public void setYunCallBack(YunCallBack yunCallBack){

        this.yunCallBack = yunCallBack;

    }

    public void sendMessage(final Context context, String hasId, String text){

        Log.e("sendMessage", hasId);

        try {

            ECMessage msg = ECMessage.createECMessage(ECMessage.Type.TXT);

            msg.setTo(hasId);

            msg.setBody(new ECTextMessageBody(text));

            ECChatManager manager = ECDevice.getECChatManager();

            manager.sendMessage(msg, new ECChatManager.OnSendMessageListener() {

                @Override
                public void onSendMessageComplete(ECError error, ECMessage message) {

                    if(message == null) {

                        return;

                    }

                }

                @Override
                public void onProgress(String msgId, int totalByte, int progressByte) {}

            });

        } catch (Exception e) {

            Log.e("ECSDK_Demo", "send message fail , e=" + e.getMessage());

            Toast.makeText(context, "推送发送异常", Toast.LENGTH_SHORT).show();

        }

    }

    public void sendGroupMessage(Context context, String text){

        try {

            ECMessage msg = ECMessage.createECMessage(ECMessage.Type.TXT);

            msg.setForm(userId);

            msg.setMsgTime(System.currentTimeMillis());

            msg.setTo(groupId);

            msg.setSessionId(groupId);

            msg.setDirection(ECMessage.Direction.SEND);

            msg.setBody(new ECTextMessageBody(text));

            ECChatManager manager = ECDevice.getECChatManager();

            manager.sendMessage(msg, new ECChatManager.OnSendMessageListener() {

                @Override
                public void onSendMessageComplete(ECError error, ECMessage message) {

                    if(message == null) {

                        return ;

                    }

                }

                @Override
                public void onProgress(String msgId, int totalByte, int progressByte) {}

            });

        } catch (Exception e) {

            Toast.makeText(context, "推送发送异常", Toast.LENGTH_SHORT).show();

        }

    }

    public interface YunCallBack{

        void connError();

        void loginSucceed();

        void otherLogin();

        void onReceivedMessage(ECMessage ecMessage);

    }

}
